using System;
using Avalonia.Controls;
using Avalonia.Interactivity;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls.Documents;
using Avalonia.Threading;
using DialogHostAvalonia;

namespace AvaloniaApplication1;

public partial class MainWindow : Window
{
    private SocketClient socketClient;

    private CustomDialog customDialog;
    
    // private Thread clientThread;
    private Task receiveTask;
    public MainWindow()
    {
        InitializeComponent();
        
        socketClient= new SocketClient();
        customDialog = new CustomDialog(){Height=400, Width=400};
        this.Closing += (sender, args) =>
        {
            socketClient.Disconnect();
        };
    }

    private void Btn_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine("111111");
    }

    /// <summary>
    /// 连接服务器
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private async void BtnConnect_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            await socketClient.ConnectAsync(Ip.Text,8000);
            receiveTask = Task.Run( () =>  RecvAsyncWork());
            Console.WriteLine("已连接上");
        }
        catch (Exception ex)
        {
            customDialog.Test(ex.Message);

        }

    }
    

    private void RecvAsyncWork()
    {
        while (true)
        {
          Task<string> result =   socketClient.ReceiveDataAsync();
          string data = result.Result; 
          Console.WriteLine(data);
          Dispatcher.UIThread.InvokeAsync(() =>
          {
              TextBox1.Text = data;
          });

        }
    }
    
}